<?php

defined('SYSPATH') or die('Access error!');

class Model_Q2a_Answer extends Model_Q2a_Post
{

    /**
     * 插入问题
     * @param array $data
     * @return type
     */
    public function insert_answer($data)
    {
        return $this->insert_post($data);
    }

    public function get_answer_by_parent_id($id, $where_arr = array())
    {
        $where = " WHERE p.post_type='" . Q2A_POST_TYPE_ANSWER . "'";
        $where .=!empty($id) ? ' AND ' . 'p.parent_id=' . $id : '';
        if (count($where_arr) > 0)
        {
            if (isset($where_arr['is_top']))
            {
                $where .=' AND p.is_top=' . $where_arr['is_top'];
            }
        }
        $where .= ' ORDER BY p.position,p.id';

        $sql = "SELECT p.id,p.is_top,p.add_time,p.content,p.up_votes,p.down_votes,p.comment_count,u.username,u.avatar,u.id as user_id " .
                "FROM " . $this->table . " AS p " .
                "LEFT JOIN " . $this->db->get_table('user') . " AS u ON p.user_id = u.id " . $where;


        $data = $this->get_page_list($sql, 10);

        $temp = array();
        if (count($data['list']) > 0)
        {
            foreach ($data['list'] as $value)
            {
                $value['avatar_path'] = Model::factory('user')->create_avatar_path($value['user_id'], $value['avatar']);

                //获取问题的评论
                $value['comments'] = Model_Q2a_Comment::factory('q2a_comment')->get_comment_by_parent_id($value['id']);
                $value['comments_count'] = count($value['comments']);
                $temp[] = $value;
            }
            //处理普通问题或者是置顶问题
            $data['list'] = $this->handle_answer_list($temp);
            unset($temp);
        }
        return count($data) > 0 ? $data : array();
    }

    public function handle_answer_list($data)
    {
        $answer_list = array();
        foreach ($data as $value)
        {
            if ($value['is_top'] == 1)
            {
                $answer_list['top_answer'][] = $value;
                continue;
            }
            $answer_list['common_answer'][] = $value;
        }

        return $answer_list;
    }

    public function get_answer_list($data)
    {
        $post_list = $this->get_post_list($data);
        $data = array();
        if(Arr::validate_arr($post_list['list'])){
            $answer_id_list = Arr::recursion_get_value_arr($post_list['list'],'parent_id');
            if(Arr::validate_arr($answer_id_list)){
                $id_in = $this->get_in($answer_id_list);
               $question_list = $this->get_post_list(' WHERE p.id'.$id_in);
            }
        }
        return $question_list;
    }

}